package handlers

import (
	"car-master/models"
	"github.com/gin-gonic/gin"
	"strconv"
)

func RoleNode(c *gin.Context) {
	rid, _ := strconv.Atoi(c.PostForm("rid"))
	nid, _ := strconv.Atoi(c.PostForm("nid"))
	if rid == 0 || nid == 0 {
		c.JSON(200, gin.H{
			"code": 400,
			"msg":  "字段不能为空",
		})
		return
	}
	data := models.NodeRole{

		Nid: nid,
		Rid: rid,
	}
	err := models.DB.Create(&data).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 400,
			"msg":  "添加失败",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "添加成功",
	})
}

func UserRoleList(c *gin.Context) {
	rid := c.Query("rid")

	/*
		SELECT*FROM
		roles
		LEFT JOIN user_roles ON user_roles.rid= roles.id
		WHERE user_roles.rid=1
	*/
	var user []models.Role
	models.DB.Table("roles").
		Joins("LEFT JOIN user_roles ON user_roles.rid= roles.id").
		Where("user_roles.rid=?", rid).
		Find(&user)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "查询成功",
		"list": user,
	})
}
func RoleNodeList(c *gin.Context) {
	nid := c.Query("nid")
	/*
		SELECT*FROM
		nodes
		LEFT JOIN node_roles ON node_roles.nid=nodes.id
		WHERE node_roles.nid=1
	*/
	var arr []models.Node
	models.DB.Table("nodes").
		Joins("LEFT JOIN node_roles ON node_roles.nid=nodes.id").
		Where("node_roles.nid=?", nid).
		Find(&arr)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "查询成功",
		"list": arr,
	})
}
